package com.example.bankingsystemandroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;

import com.csc.bankingsystem.core.dto.AccountInfoDTO;
import com.example.bankingsystemandroid.Holder.InfoHolder;
import com.example.bankingsystemandroid.utils.PropertiesConfig;
import com.example.bankingsystemandroid.utils.PropertyManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class AccountFragment extends Fragment {
	private TextView balanceTextView;
	private TextView stateTextView;
	private TextView accountTypeTextView;
	private TextView idCardNumTextView;
	private ArrayList<AccountInfoDTO> listUser = new ArrayList<AccountInfoDTO>();
	private ArrayList<String> listAccount = new ArrayList<String>();
	ArrayAdapter<String> dataAdapter = null;
	private TableLayout tableView;

	private ProgressBar mProgress;

	public AccountFragment() {

		GetAccountInfoTask accountInfoTask = new GetAccountInfoTask();
		accountInfoTask.execute();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.fragment_account, container, false);
		setTableView((TableLayout) v.findViewById(R.id.table_account_fragment));

		mProgress = (ProgressBar) v
				.findViewById(R.id.progress_bar_fragment_account);
		mProgress.bringToFront();
		mProgress.setIndeterminate(true);
		mProgress.setVisibility(View.VISIBLE);
		tableView.setVisibility(View.INVISIBLE);
		setBalanceTextView((TextView) tableView
				.findViewById(R.id.balance_account_fragment));
		setStateTextView((TextView) tableView
				.findViewById(R.id.state_account_fragment));
		setAccountTypeTextView((TextView) tableView
				.findViewById(R.id.accountType_account_fragment));
		setIdCardNumTextView((TextView) tableView
				.findViewById(R.id.idCardNum_account_fragment));

		// Spinner element
		Spinner spinner = (Spinner) tableView
				.findViewById(R.id.account_spinner_fragment_account);
		dataAdapter = new ArrayAdapter<String>(getActivity(),
				R.drawable.my_spinner, listAccount);
		// Drop down layout style - list view with radio button
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// attaching data adapter to spinner
		spinner.setAdapter(dataAdapter);
		// Spinner click listener
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				AccountInfoDTO userInfo = listUser.get(position);
				balanceTextView.setText(userInfo.getAmount().toString()
						+ " VND");
				stateTextView.setText(userInfo.getState().toString());
				accountTypeTextView.setText(userInfo.getAccountType()
						.toString());
				idCardNumTextView
						.setText(userInfo.getIdCardNumber().toString());

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});

		return v;

	}

	private class GetAccountInfoTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPostExecute(Void result) {
			listUser = InfoHolder.getAccountInfoList();
			for (AccountInfoDTO account : listUser) {
				listAccount.add(account.getNumber());
			}
			dataAdapter.notifyDataSetChanged();
			if (mProgress.getVisibility() == View.VISIBLE) {
				mProgress.setVisibility(View.GONE);
			}
			if (tableView.getVisibility() == View.INVISIBLE) {
				tableView.setVisibility(View.VISIBLE);
			}
			super.onPostExecute(result);
		}

		@Override
		protected Void doInBackground(Void... params) {
			/*
			 * Create the POST request
			 */
			String serverIP = PropertiesConfig
					.getProperty(PropertyManager.SERVER_IP);
			String serverPort = PropertiesConfig
					.getProperty(PropertyManager.SERVER_PORT);

			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost("http://" + serverIP + ":"
					+ serverPort + "/bankingsystem/api/get-account-info");
			// Request parameters and other properties.

			try {

			} catch (Exception e) {
				// TODO: handle exception
			}
			/*
			 * Execute the HTTP Request
			 */
			try {
				httpPost.addHeader("Cookie",
						"JSESSIONID=" + InfoHolder.getSessionId());
				HttpResponse response = httpClient.execute(httpPost);
				HttpEntity respEntity = response.getEntity();

				if (response != null) {
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(response.getEntity()
									.getContent(), "UTF-8"));

					StringBuilder builder = new StringBuilder();
					for (String line = null; (line = reader.readLine()) != null;) {
						builder.append(line).append("\n");
					}
					JSONTokener tokener = new JSONTokener(builder.toString());
					JSONArray finalResult = new JSONArray(tokener);

					ArrayList<AccountInfoDTO> accountInfoList = new ArrayList<AccountInfoDTO>();
					Gson gson = new Gson();
					Type collectionType = new TypeToken<ArrayList<AccountInfoDTO>>() {
					}.getType();
					accountInfoList = gson.fromJson(finalResult.toString(),
							collectionType);
					InfoHolder.setAccountInfoList(accountInfoList);
				}
			} catch (ClientProtocolException e) {
				// writing exception to log
				e.printStackTrace();
			} catch (IOException e) {
				// writing exception to log
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
	}

	public TextView getBalanceTextView() {
		return balanceTextView;
	}

	public void setBalanceTextView(TextView balanceTextView) {
		this.balanceTextView = balanceTextView;
	}

	public TextView getStateTextView() {
		return stateTextView;
	}

	public void setStateTextView(TextView stateTextView) {
		this.stateTextView = stateTextView;
	}

	public TextView getAccountTypeTextView() {
		return accountTypeTextView;
	}

	public void setAccountTypeTextView(TextView accountTypeTextView) {
		this.accountTypeTextView = accountTypeTextView;
	}

	public TextView getIdCardNumTextView() {
		return idCardNumTextView;
	}

	public void setIdCardNumTextView(TextView idCardNumTextView) {
		this.idCardNumTextView = idCardNumTextView;
	}

	public ArrayList<String> getListAccount() {
		return listAccount;
	}

	public void setListAccount(ArrayList<String> listAccount) {
		this.listAccount = listAccount;
	}

	public TableLayout getTableView() {
		return tableView;
	}

	public void setTableView(TableLayout tableView) {
		this.tableView = tableView;
	}

}